package com.kdzy.lshy.common_server.common;

import com.kdzy.lshy.common_server.common.wechart.VisitUrl;
import com.kdzy.lshy.common_server.common.wechart.WechartCommon;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import redis.clients.jedis.Jedis;

/**
 * spring加载完毕后初始化token 及后续全局获取token
 * 
 * @author cly
 *
 */
@Configuration
public class TimingUpdateToKen {

	private static final Logger logger = LoggerFactory.getLogger(TimingUpdateToKen.class);

	@Bean
	public String init() {
		final long timeInterval = 1000 * 60 * 59;
		Runnable runnable = () -> {
			logger.info("更新了token,更新间隔" + 1000 * 60 * 59);
			// -----------------获取微信小程序token------------------------------------------------------------------------------------
			try {
				logger.info("url：" + String.format(WechartCommon.get_access_token_url, WechartCommon.appid, WechartCommon.secret));

				// 向微信服务器发送请求获取token
				String httpsResult = VisitUrl.sendHttpsGet(String.format(WechartCommon.get_access_token_url, WechartCommon.appid, WechartCommon.secret),null);
				// 解析返回参数
				JSONObject obj = JSON.parseObject(httpsResult);

				// 更新微信小程序token
				if (obj.get("access_token") != null) {
					// 获取小程序token 返回示例: {"access_token":"ACCESS_TOKEN","expires_in":7200}
					WechartCommon.access_token = obj.getString("access_token");

					// TODO 将token存入redis中，成为全局token
					// 将token保存到redis中
					Jedis jedis = new Jedis("140.143.210.101", 6379);
					jedis.auth("q1w2e3r4t5");
					jedis.set("wechartToken", WechartCommon.access_token);

					logger.info("获取小程序token成功:" + obj.getString("access_token"));
					jedis.close();
				} else if (obj.get("errcode") != null) {
					// 没有获小程序token 返回示例: {"errcode":40013,"errmsg":"invalid appid"}
					logger.error("没有获取到小程序token,错误信息:" + obj.get("errcode") + "错误信息:" + obj.get("errmsg"));
				}
			} catch (Exception e) {
				logger.error("小程序获取token异常:" + ExceptionDetailMessage.getExceptionDetail(e));
			}

			try {
				Thread.sleep(timeInterval);
			} catch (InterruptedException e) {
				logger.error("定时获取token线程异常" + e);
			}
		};

		Thread thread = new Thread(runnable);
		thread.start();
		return null;
	}
}
